package org.makcro.sms.services.chat.web.client.mvc.view;

import org.makcro.sms.services.chat.web.client.AppEvents;
import org.makcro.sms.services.chat.web.client.Constants;
import org.makcro.sms.services.chat.web.client.widgets.MainPanel;
import org.makcro.sms.services.chat.web.client.widgets.MainTabPanel;
import org.makcro.sms.services.chat.web.client.widgets.MessagesTabItem;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.event.EventType;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Controller;
import com.extjs.gxt.ui.client.mvc.View;
import com.extjs.gxt.ui.client.widget.Viewport;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.google.gwt.user.client.ui.RootPanel;

public class MainView extends View {

	private Viewport viewport;
	private MainPanel mainPanel;
	private MainTabPanel mainTabPanel;
	private MessagesTabItem mainTabItem; 
	
	public MainView(Controller controller) {
		super(controller);
	}

	@Override
	protected void initialize() {
		super.initialize();
		viewport = new Viewport();
		
		Registry.register( Constants.Ui.MAIN_TAB_PANEL, getMainTabPanel() );	
		Registry.register( Constants.Ui.MESSAGES_TAB_ITEM, getMessagesTabItem() );
	}

	@Override
	protected void handleEvent(AppEvent event) {
		EventType type = event.getType();
		
		if (type == AppEvents.LoginSuccessful) {
			onInit(event);
		} 
	}

	private void onInit(AppEvent event) {
		viewport.setLayout(new FitLayout());
		getMainTabPanel().add( getMessagesTabItem() );
		viewport.add( getMainPanel() );
		RootPanel.get().add(viewport);
	}
	
	public MainTabPanel getMainTabPanel() {
		if(this.mainTabPanel == null){
			this.mainTabPanel = new MainTabPanel();
		}
		return mainTabPanel;
	}
	
	public MainPanel getMainPanel() {
		if (this.mainPanel == null) {
			this.mainPanel = new MainPanel();
			this.mainPanel.add( getMainTabPanel() );
		}
		return mainPanel;
	}
	
	public MessagesTabItem getMessagesTabItem() {
		if(this.mainTabItem == null){
			this.mainTabItem = new MessagesTabItem();
		}
		return mainTabItem;
	}

}
